package fr.emse.tatiana.remotecontrol;

import fr.emse.tatiana.replayable.Replayable;

public class Schedule {
	
	private ScheduledTraceEvent first;
	private ScheduledTraceEvent last;
	private ScheduledTraceEvent current;

	public Schedule() {
		this.first=null;
		this.last=first;
		current = null;
	}
	
	public void insertEvent(TraceEvent te) {
		ScheduledTraceEvent next = first;
		ScheduledTraceEvent previous = null;
		while (next!=null && te.getTime()>next.getTime()) {
			previous = next;
			next = next.getNext();
		}
		
		ScheduledTraceEvent n = new ScheduledTraceEvent(te);
		if (previous==null) {
			n.setNext(first);
			first = n;
		} else {
			n.setNext(previous.getNext());
			previous.setNext(n);
		}
		if (next==null) {
			last = n;
		}
	}
	
	public boolean isEmpty() {
		return this.first==null;
	}
	
	public ScheduledTraceEvent next() {
		if (current == null) {
			current = first;
		} else {
			current = current.getNext();
		}
		return current;
	}
	
	public ScheduledTraceEvent goTo(long time) {
		if (current == null || current.getTime()>time) current = first;
		while (current!=null && current.getTime()<time) {
			current = current.getNext();
		}
		return current;
	}
	
	public void print() {
		ScheduledTraceEvent current=first;
		while (current!=null) {
			System.err.println("schedule:"+current.getTime()+" "+current.getTarget());
			current = current.getNext();
		}
	}
	
	public ScheduledTraceEvent getFirst() {
		return first;
	}

	public ScheduledTraceEvent getLast() {
		return last;
	}

	public long getLastTime() {
		return (this.last==null)?0:this.last.getTime();
	}
		
	public long getFirstTime() {
		if( this.first!=null ) {
			return (this.first.getTime());
		} else {
			return 0;
		}
	}

	public ScheduledTraceEvent getCurrent() {
		return current;
	}

	public void removeReplayer(Replayable r) {
		ScheduledTraceEvent next = first;
		ScheduledTraceEvent previous = null;
		while (next!=null) {
			
			if (next.getTarget() == r) {
				next.disableEvent();
				if (current == next) {
					current = previous;
				}
				if (previous == null) {
					first=next.getNext();
				} else {
					previous.setNext(next.getNext());
				}
			} else {
				previous = next;
			}
			next = next.getNext();
		}
		last = previous;
		
	}
	
}
